//HTTPS_HOST 接口地址。
const HTTPS_HOST = "https://www.baidu.com/wechat"

function dealResult(res, resolve, reject) {
  console.log('接口response：',res);
  if (res.errMsg == 'openDocument:ok') {
    resolve(res);
  } else if (res.data.status !== 400) {
    resolve(res.data);
  } else {
    wx.showToast({
      title: res.data.message,
      icon: 'none',
      duration: 2000
    })
    reject(res.data);
  }
}

/**
 * @param {Object} options 请求配置对象 参考wx实际接口文档
 * @param {String} type 接口类型 默认request, downloadFile=下载文件预览，uploadFile=上传文件
 * */
function request(options, type) {
  let params = options.data || {};
  return new Promise((resolve, reject) => {
    console.log(token)
    // 通用接口拦截
    if (typeof type == 'undefined') {
      wx.request({
        header: {
          'content-type': 'application/json',
          'appSign': 'wxapp'
        },
        ...options,
        data: params,
        url: HTTPS_HOST + options.url,
        success(res) {
          dealResult(res, resolve, reject);
        },
        fail(err) {
          wx.hideLoading()
          // 错误处理
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '请求超时,请检查网络！',
            success: function () {

            }
          })
          // reject(err);
        }
      });
    } else if (typeof type != 'undefined' && type == 'downloadFile') {
      // 下载预览
      wx.downloadFile({
        ...options,
        url: HTTPS_HOST + options.url,
        header: {
          'appSign': 'wxapp'
        },
        success(res) {
          const filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            fileType: 'pdf',
            success: function (res) {
              console.log('打开文档成功');
              dealResult(res, resolve, reject);
            },
            fail(err) {
              console.log('打开文档失败:', err)
            }
          })
        },
        fail(err) {
          reject(err);
        }

      })
    } else if (typeof type != 'undefined' && type == 'uploadFile') {
      wx.uploadFile({
        ...options,
        url: HTTPS_HOST + options.url,
        header: {
          'appSign': 'wxapp'
        },
        success(res) {
          const data = res.data;
          dealResult(res, resolve, reject);
        },
        fail(err) {
          console.log('err:',err)
          reject(err);
        },
        complete(err){
          console.log('comp:',err)
            reject(err);
        }
      })
    }

  })
}


export default request;